package com.weijin.service.RedisService;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * @Author WeiJin
 * @Version 1.0
 * @Date 2025/3/21 9:34
 */
@Service
public class MessageRankService {

    private static final String KEY = "chat:message_rank";

    @Resource
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 增加用户发送消息记录数
     * @param userId 用户id
     */
    public void addMessageCount(String userId){
        redisTemplate.opsForZSet().incrementScore(KEY,userId,1);
    }

    /**
     * 获取发送内容前10的用户id
     * @return 用户id
     */
    public Set<ZSetOperations.TypedTuple<String>> getTop10(){
        return redisTemplate.opsForZSet().reverseRangeWithScores(KEY,0,9);
    }

    /**
     * 每天凌晨清理7天前的排行榜
     */
    @Scheduled(cron = "0 0 0 * * ?")
    public void cleanOldRanks() {
        long now = System.currentTimeMillis();
        redisTemplate.opsForZSet().removeRangeByScore(
                KEY, 0, now - 7 * 86400_000
        );
    }

    /**
     * 判断用户是否一分钟发送超过30条记录
     * @param userId 用户
     * @return true 或者 false
     */
    public boolean checkRateLimit(String userId) {
        String key = "chat:rate_limit:" + userId;
        Long count = redisTemplate.opsForValue().increment(key);
        redisTemplate.expire(key, 1, TimeUnit.MINUTES);
        return count != null && count <= 30; // 每分钟30条
    }


}
